package com.zkdcloud.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zkdcloud.domain.Admin;
import com.zkdcloud.domain.User;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * token Util
 * @author zk123
 * @version 2018/4/30
 */
public class TokenUtil {
    /**
     * 制作admin tocken
     *
     * @return tocken
     */
    public static String makeAdminToken(Admin admin){
        try {
            return Base64.getEncoder().encodeToString(JSON.toJSONString(admin).getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * userToken
     *
     * @param user user
     * @return token
     */
    public static String makeUserToken(User user){
        try {
            return Base64.getEncoder().encodeToString(JSON.toJSONString(user).getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据token获取admin
     *
     * @param token token
     * @return admin
     */
    public static Admin getTokenAdmin(String token){
        try {
            String adminJSON = new String(Base64.getDecoder().decode(token),"UTF-8");
            JSON ja = JSON.parseObject(adminJSON);
            return JSONObject.toJavaObject(ja,Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据token获取user
     *
     * @param token token
     * @return user
     */
    public static User getTokenUser(String token){
        try {
            String adminJSON = new String(Base64.getDecoder().decode(token),"UTF-8");
            JSON ja = JSON.parseObject(adminJSON);
            return JSONObject.toJavaObject(ja,User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
